package com.bhh.myservlet.processor;

import com.bhh.myservlet.requestandresponse.Request;
import com.bhh.myservlet.requestandresponse.Response;
import com.bhh.myservlet.Util;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Servlet;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

/**
 * @author bhh
 * @description 处理动态资源
 * <p>
 * 如何处理?
 * <p>
 * 根据 request 查找类, 加载对应类, 获取类的 Class文件
 * 获取到 Class文件后, 利用反射来获取到实例
 * 实例调用 service()方法
 * @date Created in 2021-04-15 17:07
 * @modified By
 */
@Slf4j
public class ServletProcessor {
    public URLClassLoader getServletLoader() throws MalformedURLException {
        File file = new File(Util.WEB_ROOT);
        URLClassLoader urlClassLoader =
                new URLClassLoader(new URL[]{file.toURI().toURL()});
        return urlClassLoader;
    }

    public Servlet getServlet(URLClassLoader urlClassLoader, Request request)
            throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        /*
         * request : /servlet/TimeServlet
         * */
        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);

        Arrays.stream(urlClassLoader.getURLs()).forEach(System.out::println);
        Class<Servlet> servletClass =
                (Class<Servlet>) urlClassLoader.loadClass(servletName);
        return servletClass.newInstance();
    }

    public void process(Request request, Response response) {
        try {
            URLClassLoader servletLoader = getServletLoader();
            Servlet servlet = getServlet(servletLoader, request);
            servlet.service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
